//
//  WHHeaderView.m
//  AddressBook
//
//  Created by 王涵 on 2020/8/5.
//  Copyright © 2020 wh. All rights reserved.
//

#import "WHHeaderView.h"
#import "MacroDefinition.h"
#import "Masonry.h"
#import "UIImageTool.h"

@interface WHHeaderView ()

@property (nonatomic, strong) UIImageView *headerImage;
@property (nonatomic ,strong) UILabel *nameLabe;
@property (nonatomic, assign) CGFloat imageHeight;

@end

@implementation WHHeaderView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = UIColor.whiteColor;
        [self initWithView];
    }
    return self;
}
//添加视图
- (void)initWithView
{
    [self addSubview:self.headerImage];
    [self addSubview:self.nameLabe];
}
//添加数据
- (void)setDataWithImageStr:(NSString *)imageStr nameStr:(NSString *)nameStr
{
    UIImage *image = [UIImageTool Base64StrToUIImage:imageStr];
    self.headerImage.image = image;
    self.nameLabe.text = nameStr;
}

- (void)setDataWithImageStr:(NSString *)imageStr
{
    UIImage *image = [UIImageTool Base64StrToUIImage:imageStr];
    self.headerImage.image = image;
}
//设置布局
- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat imageX = (self.frame.size.width - self.imageHeight)/2 ;
    CGFloat imageY = (self.frame.size.height - self.imageHeight)/2;
    self.headerImage.frame = CGRectMake(imageX, imageY, self.imageHeight, self.imageHeight);
    self.headerImage.layer.cornerRadius = self.imageHeight/2;
    
    CGFloat nameLabelY = imageY + self.imageHeight + 2;
    CGFloat nameLabelH = self.imageHeight/4;
    CGFloat fontSize = self.imageHeight/5.5;
    self.nameLabe.font = [UIFont systemFontOfSize:fontSize];
    self.nameLabe.frame = CGRectMake(0, nameLabelY, self.frame.size.width, nameLabelH);
}
 //image点击事件
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer
{
    if (self.headerDelegate && [self.headerDelegate performSelector:@selector(imageAction)]) {
        [self.headerDelegate imageAction];
    }
}
#pragma mark - 懒加载
- (UIImageView *)headerImage
{
    if (!_headerImage) {
        _headerImage = [[UIImageView alloc] init];
        _headerImage.backgroundColor = UIColor.lightGrayColor;
        _headerImage.layer.cornerRadius = self.imageHeight/2;
        _headerImage.layer.masksToBounds = YES;
        _headerImage.userInteractionEnabled = YES;
        UIGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        [_headerImage addGestureRecognizer:singleTap];
    }
    return _headerImage;
}

- (UILabel *)nameLabe
{
    if (!_nameLabe) {
        _nameLabe = [[UILabel alloc] init];
        _nameLabe.textColor = UIColor.blackColor;
        _nameLabe.textAlignment = NSTextAlignmentCenter;
    }
    return _nameLabe;
}

- (CGFloat)imageHeight
{
    return self.frame.size.height/2;
}

@end
